const request = require("request");

interface DefaultOptions<T> {
  json: boolean;
  timeout: number;
  encoding: null | string;
  headers: T
}

interface RequestOption {
  url: string,
  method: "GET" | "POST",
  json: boolean,
  timeout: number,
  qs?: any,
  form?: any
}

interface HeaderType {
  "content-type": "application/json",
}

const defaultOptions: DefaultOptions<HeaderType> = {
  json: true,
  timeout: 30000,  // 设置请求超时，单位是毫秒
  encoding: null,
  headers: {
    "content-type": "application/json",
  },
};

function get(url: string, params?: any): Promise<void> {
  return new Promise((resolve, reject) => {
    let option: RequestOption = {
      url,
      method: "GET",
      ...defaultOptions,
      qs: params // 进行GET请求时，此处的参数一定是qs,请注意，如果是POST请求，参数是form
    };
    request(option, function(error: any, response: any, body: any) {
        if (!error && response.statusCode == 200) {
          resolve(body)
        }else{
          reject(error);
        }
    });
  });
};

function post(url: string, params: any): Promise<void> {
  return new Promise((resolve, reject) => {
    let option: RequestOption = {
      url,
      method: "POST",
      ...defaultOptions,
      form: params
    };
    request(option, function(error: any, response: any, body: any) {
        if (!error && response.statusCode == 200) {
          resolve(body)
        }else{
          reject(error);
        }
    });
  });
}

export { post, get }